import axios from "axios";
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import { stringify } from "qs";
import NProgress from "../progress";
// import { getToken } from "@/utils/auth"; // 你可以根据实际情况引入

const defaultConfig: AxiosRequestConfig = {
  baseURL: import.meta.env.VITE_API_BASE_URL, // 推荐用环境变量 
  timeout: 10000,
  headers: {
    Accept: "application/json, text/plain, */*",
    "Content-Type": "application/json",
    "X-Requested-With": "XMLHttpRequest",
  },
  paramsSerializer: params => stringify(params, { arrayFormat: "brackets" }),
};

class PureHttp {
  private instance: AxiosInstance;

  constructor() {
    this.instance = axios.create(defaultConfig);
    this.setupInterceptors();
  }

  private setupInterceptors() {
    // 请求拦截
    this.instance.interceptors.request.use(
      config => {
        NProgress.start();
        // 设置 token
        // const token = getToken();
        // if (token) {
        //   config.headers = config.headers || {};
        //   config.headers["Authorization"] = `Bearer ${token}`;
        // }
          return config;
      },
      error => {
        NProgress.done();
        return Promise.reject(error);
      }
    );

    // 响应拦截
    this.instance.interceptors.response.use(
      (response: AxiosResponse) => {
        NProgress.done();
        return response.data;
      },
      error => {
        NProgress.done();
        return Promise.reject(error);
      }
    );
  }

  public async request<T = any>(config: AxiosRequestConfig): Promise<AxiosResponse<T>> {
    return await this.instance.request<T>(config);
  }

  public async get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    const response = await this.instance.get<T>(url, config);
    return response as T;
  }

  public async post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
    return await this.instance.post<T>(url, data, config);
  }

  public async put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
    return await this.instance.put<T>(url, data, config);
  }

  public async delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<T>> {
    return await this.instance.delete<T>(url, config);
  }

}

export const http = new PureHttp();
